#include "mainwindow.h"
#include <QMenu>
#include <QMenuBar>
#include <QAction>
#include <QString>
#include <QUndoStack>
#include "commands.h"
#include <QMessageBox>
#include <QFileDialog>
#include <QToolBar>
#include <QLabel>
#include <QGraphicsScene>
#include <QGraphicsSceneMouseEvent>
#include <QGraphicsView>
#include <QGridLayout>
#include <QStatusBar>
#include <QColorDialog>
#include <QIcon>
#include "model.h"
#include "events.h"
#include "view.h"
#include "line.h"
#include "circle.h"
#include "select.h"
#include <QGraphicsRectItem>
#include <QSlider>
#include <QPushButton>
#include <iostream>
#include <qmath.h>
#include <QList>
#include <QGraphicsItem>
#include <QToolButton>
#include <QtSvg/QSvgGenerator>
#include <QtSvg/QGraphicsSvgItem>
#include <QPainter>
#include <QBrush>
#include <QTextDocument>
#include <QTextEdit>
#include <QFile>
#include <QTextStream>


MainWindow::MainWindow(Model& model):m_model(model)
{

    m_currentLine = NULL;
    m_currentCircle = NULL;
    m_currentSelection = NULL;
    m_arcState=0;
    m_drawType = 0;
    m_editType = 1;
    m_isEdit = false;
    m_mouseHold = false;
    m_selectRect = new QGraphicsRectItem(0,0,1,1);
    QPen t_pen(Qt::DashLine);
    QBrush t_brush(Qt::NoBrush);
    m_selectRect->setPen(t_pen);
    m_selectRect->setBrush(t_brush);
    m_selectCircle = new QGraphicsEllipseItem(0,0,10,10);
    t_pen.setStyle(Qt::SolidLine);
    t_brush.setStyle(Qt::SolidPattern);
    t_brush.setColor(Qt::yellow);
    m_selectCircle->setPen(t_pen);
    m_selectCircle->setBrush(t_brush);


    createActions();
    buildMenuBar();
    buildToolBars();

    //Layout to glue the QGraphicsScene into the mainwindow
    QGridLayout* g = new QGridLayout();
    QWidget *mainWidget = new QWidget();
    mainWidget->setLayout(g);
    setCentralWidget(mainWidget);

    //Create the view, enable mouse tracking and setting scene from the model
    m_view = new View(this);
    m_view->setScene(&m_model);
    m_view->setMouseTracking(true);
    //m_oldView = new QRect(m_view->rect());

    m_penWidth = new QSlider(Qt::Horizontal);
    connect(m_penWidth, SIGNAL(valueChanged(int)), this, SLOT(setThickness()));

    //Add it to the layout
    g->addWidget(m_view);

    setWindowTitle(tr("AutoPAC 1.0"));
    setWindowIcon(QIcon(":/resources/AutoPAC.jpg"));
    buildStatusBar();
}
void MainWindow::createActions()
{
    // New Action
    m_newAct = new QAction(QString(tr("New")), this);
    m_newAct->setIcon(QIcon(":/resources/new.png"));
    m_newAct->setShortcut(QKeySequence::New);
    m_newAct->setStatusTip(tr("Create a new AutoPAC file"));
    connect(m_newAct, SIGNAL(triggered()), this, SLOT(newProject()));

    // Open Action
    m_openAct = new QAction(QString(tr("Open")), this);
    m_openAct->setIcon(QIcon(":/resources/open.png"));
    m_openAct->setShortcut(QKeySequence::Open);
    m_openAct->setStatusTip(tr("Open an existing AutoPAC file"));
    connect(m_openAct, SIGNAL(triggered()), this, SLOT(openFile()));

    // Save Action
    m_saveAct = new QAction(QString(tr("Save")), this);
    m_saveAct->setIcon(QIcon(":/resources/save.png"));
    m_saveAct->setShortcut(QKeySequence::Save);
    m_saveAct->setStatusTip(tr("Save the current AutoPAC project to an AutoPAC file"));
    connect(m_saveAct, SIGNAL(triggered()), this, SLOT(saveFile()));

    // Save As Action
    m_saveAsAct = new QAction(QString(tr("Save as")), this);
    m_saveAsAct->setIcon(QIcon(":/resources/save.png"));
    m_saveAsAct->setShortcut(QKeySequence::SaveAs);
    m_saveAsAct->setStatusTip(tr("Save the current AutoPAC project to an AutoPAC file"));
    connect(m_saveAsAct, SIGNAL(triggered()), this, SLOT(saveAsFile()));

    // Exit Action
    m_exitAct = new QAction(QString(tr("Exit")), this);
    m_exitAct->setShortcut(QKeySequence::Quit);
    connect(m_exitAct, SIGNAL(triggered()), this, SLOT(close()));

    // Redraw Action
    m_redrawAct = new QAction(QString(tr("Redraw")), this);
    m_redrawAct->setIcon(QIcon(":/resources/redraw.png"));
    m_redrawAct->setShortcut(QKeySequence::Refresh);
    m_redrawAct->setStatusTip(tr("Clear all the screen and redraw it"));

    // Redo Action
    m_redoAct = new QAction(QString(tr("Redo")), this);
    m_redoAct->setIcon(QIcon(":/resources/redo.png"));
    m_redoAct->setShortcut(QKeySequence::Redo);
    m_redoAct->setStatusTip(tr("Redo last command"));
    connect(m_redoAct, SIGNAL(triggered()), this, SLOT(redo()));

    // Undo Action
    m_undoAct = new QAction(QString(tr("Undo")), this);
    m_undoAct->setIcon(QIcon(":/resources/undo.png"));
    m_undoAct->setShortcut(QKeySequence::Undo);
    m_undoAct->setStatusTip(tr("Undo last command"));
    connect(m_undoAct, SIGNAL(triggered()), this, SLOT(undo()));

    // Select Action
    m_selectAct = new QAction(QString(tr("Select")), this);
    m_selectAct->setCheckable(true);
    m_selectAct->setIcon(QIcon(":/resources/select.png"));
    m_selectAct->setStatusTip(tr("Make selection"));
    connect(m_selectAct, SIGNAL(triggered()), this, SLOT(select()));

    // Copy Action
    m_copyAct = new QAction(QString(tr("Copy")), this);
    m_copyAct->setIcon(QIcon(":/resources/copy.png"));
    m_copyAct->setDisabled(true);
    m_copyAct->setShortcut(QKeySequence::Copy);
    m_copyAct->setStatusTip(tr("Copy selection"));

    // Erase Action
    m_eraseAct = new QAction(QString(tr("Erase")), this);
    m_eraseAct->setIcon(QIcon(":/resources/eraser.gif"));
    m_eraseAct->setDisabled(true);
    m_eraseAct->setShortcut(QKeySequence::Delete);
    m_eraseAct->setStatusTip(tr("Delete selection"));
    connect(m_eraseAct, SIGNAL(triggered()), this, SLOT(selectErase()));

    // Rotate Action
    m_rotateAct = new QAction(QString(tr("Rotate")), this);
    m_rotateAct->setCheckable(true);
    m_rotateAct->setDisabled(true);
    m_rotateAct->setIcon(QIcon(":/resources/rotate.png"));
    m_rotateAct->setStatusTip(tr("Rotate selection"));
    connect(m_rotateAct, SIGNAL(triggered()), this, SLOT(selectRotate()));

    // Move Action
    m_moveAct = new QAction(QString(tr("Move")), this);
    m_moveAct->setCheckable(true);
    m_moveAct->setDisabled(true);
    m_moveAct->setIcon(QIcon(":/resources/move.png"));
    m_moveAct->setStatusTip(tr("Move selection"));
    connect(m_moveAct, SIGNAL(triggered()), this, SLOT(selectMove()));

    // Scale Action
    m_scaleAct = new QAction(QString(tr("Scale")), this);
    m_scaleAct->setCheckable(true);
    m_scaleAct->setDisabled(true);
    m_scaleAct->setIcon(QIcon(":/resources/scale.png"));
    m_scaleAct->setStatusTip(tr("Scale selection"));
    connect(m_scaleAct, SIGNAL(triggered()), this, SLOT(selectScale()));

    // Trim Action
    m_trimAct = new QAction(QString(tr("Trim")), this);
    m_trimAct->setDisabled(true);

    // Mirror Action
    m_mirrorAct = new QAction(QString(tr("Mirror")), this);
    m_mirrorAct->setDisabled(true);

    // Break Action
    m_breakAct = new QAction(QString(tr("Break")), this);
    m_breakAct->setDisabled(true);

    // Line Action
    m_lineAct = new QAction(QString(tr("Line")), this);
    m_lineAct->setCheckable(true);
    m_lineAct->setChecked(true);
    m_lineAct->setIcon(QIcon(":/resources/line.png"));
    m_lineAct->setStatusTip(tr("Selects line drawer"));
    connect(m_lineAct, SIGNAL(triggered()), this, SLOT(setLineDrawType()));

    // Circle Action
    m_circleAct = new QAction(QString(tr("Circle")), this);
    m_circleAct->setCheckable(true);
    m_circleAct->setIcon(QIcon(":/resources/circle.png"));
    m_circleAct->setStatusTip(tr("Selects circle drawer"));
    connect(m_circleAct, SIGNAL(triggered()), this, SLOT(setCircleDrawType()));

    // Arc Action
    m_arcAct = new QAction(QString(tr("Arc")), this);
    m_arcAct->setCheckable(true);
    m_arcAct->setIcon(QIcon(":/resources/arc.png"));
    m_arcAct->setStatusTip(tr("Selects arc drawer"));
    connect(m_arcAct, SIGNAL(triggered()), this, SLOT(setArcDrawType()));

    // Color Action
    m_colorAct = new QAction(QString(tr("Color")), this);
    m_colorAct->setIcon(QIcon(":/resources/color.png"));
    m_colorAct->setStatusTip(tr("Selects the shape color"));
    connect(m_colorAct, SIGNAL(triggered()), this, SLOT(selectColor()));

    // Thickness Action
    m_thicknessAct = new QAction(QString(tr("Thickness")), this);
    m_thicknessAct->setIcon(QIcon(":/resources/thickness.png"));
    m_thicknessAct->setStatusTip(tr("Selects the line thickness"));
    connect(m_thicknessAct, SIGNAL(triggered()), this, SLOT(selectThickness()));

    // Type Actions
    m_typeSolidAct = new QAction(QString(tr("Solid line")), this);
    m_typeSolidAct->setCheckable(true);
    m_typeSolidAct->setChecked(true);
    connect(m_typeSolidAct, SIGNAL(triggered()), this, SLOT(selectSolidLine()));
    m_typeDashAct = new QAction(QString(tr("Dash line")), this);
    m_typeDashAct->setCheckable(true);
    connect(m_typeDashAct, SIGNAL(triggered()), this, SLOT(selectDashLine()));
    m_typeDotAct = new QAction(QString(tr("Dot line")), this);
    m_typeDotAct->setCheckable(true);
    connect(m_typeDotAct, SIGNAL(triggered()), this, SLOT(selectDotLine()));
    m_typeDashDotAct = new QAction(QString(tr("Dash dot line")), this);
    m_typeDashDotAct->setCheckable(true);
    connect(m_typeDashDotAct, SIGNAL(triggered()), this, SLOT(selectDashDotLine()));
    m_typeDashDotDotAct = new QAction(QString(tr("Dash dot dot line")), this);
    m_typeDashDotDotAct->setCheckable(true);
    connect(m_typeDashDotDotAct, SIGNAL(triggered()), this, SLOT(selectDashDotDotLine()));

    // Window Action
    m_windowAct = new QAction(QString(tr("Window")), this);
    m_windowAct->setIcon(QIcon(":/resources/window.png"));
    m_windowAct->setShortcut(QKeySequence::ZoomIn);
    m_windowAct->setStatusTip(tr("Zoom in selection"));
    connect(m_windowAct, SIGNAL(triggered()), this, SLOT(zoomIn()));

    // Previous Action
    m_previousAct = new QAction(QString(tr("Previous")), this);
    m_previousAct->setIcon(QIcon(":/resources/previous.png"));
    m_previousAct->setShortcut(QKeySequence::ZoomOut);
    m_previousAct->setStatusTip(tr("Undo last zoom"));
    connect(m_previousAct, SIGNAL(triggered()), this, SLOT(undoZoom()));

    // All Action
    m_allAct = new QAction(QString(tr("All")), this);
    m_allAct->setIcon(QIcon(":/resources/all.png"));
    m_allAct->setShortcut(QKeySequence::Back);
    m_allAct->setStatusTip(tr("Show the complete scene"));
    connect(m_allAct, SIGNAL(triggered()), this, SLOT(allZoom()));

    // Help Action
    m_helpAct = new QAction(QString(tr("Help")), this);
    m_helpAct->setShortcut(QKeySequence::HelpContents);
    connect(m_helpAct, SIGNAL(triggered()), this, SLOT(help()));

    // About Action
    m_aboutAct = new QAction(QString(tr("About")), this);
    connect(m_aboutAct, SIGNAL(triggered()), this, SLOT(about()));

}
void MainWindow::buildToolBars () {

    QToolBar *fileBar = new QToolBar();
    QToolBar *editBar = new QToolBar();
    QToolBar *drawPropBar = new QToolBar();
    QToolBar *viewBar = new QToolBar();

    addToolBar(fileBar);
    addToolBar(editBar);
    addToolBar(Qt::LeftToolBarArea,drawPropBar);
    addToolBar(viewBar);

    fileBar->addAction(m_newAct);
    fileBar->addAction(m_openAct);
    fileBar->addAction(m_saveAct);

    editBar->addAction(m_redoAct);
    editBar->addAction(m_undoAct);

    editBar->addAction(m_redrawAct);

    editBar->addSeparator();

    editBar->addAction(m_selectAct);
    editBar->addAction(m_copyAct);
    editBar->addAction(m_eraseAct);
    editBar->addAction(m_rotateAct);
    editBar->addAction(m_moveAct);
    editBar->addAction(m_scaleAct);

    drawPropBar->addAction(m_lineAct);
    drawPropBar->addAction(m_circleAct);
    drawPropBar->addAction(m_arcAct);

    drawPropBar->addSeparator();

    drawPropBar->addAction(m_colorAct);
    drawPropBar->addAction(m_thicknessAct);

    QToolButton* type = new QToolButton();
    type->setPopupMode(QToolButton::InstantPopup);
    type->setIcon(QIcon(":/resources/type.png"));
    type->addAction(m_typeSolidAct);
    type->addAction(m_typeDashAct);
    type->addAction(m_typeDotAct);
    type->addAction(m_typeDashDotAct);
    type->addAction(m_typeDashDotDotAct);
    drawPropBar->addWidget(type);

    viewBar->addAction(m_windowAct);
    viewBar->addAction(m_previousAct);
    viewBar->addAction(m_allAct);

}
void MainWindow::buildMenuBar()
{
    QMenu* menu;

    menuBar()->setCornerWidget(new QLabel(tr("AutoPAC 1.0")));

    menu = menuBar()->addMenu(tr("&File"));
    menu->addAction(m_newAct);
    menu->addAction(m_openAct);
    menu->addAction(m_saveAct);
    menu->addAction(m_saveAsAct);
    menu->addSeparator();
    menu->addAction(m_exitAct);

    menu = menuBar()->addMenu("&Edit");
    menu->addAction(m_undoAct);
    menu->addAction(m_redoAct);
    menu->addAction(m_redrawAct);
    menu->addSeparator();
    menu->addAction(m_selectAct);
    menu->addAction(m_copyAct);
    menu->addAction(m_eraseAct);
    menu->addAction(m_rotateAct);
    menu->addAction(m_moveAct);
    menu->addAction(m_scaleAct);
    menu->addAction(m_trimAct);
    menu->addAction(m_mirrorAct);
    menu->addAction(m_breakAct);

    menu = menuBar()->addMenu(tr("&Draw"));
    menu->addAction(m_lineAct);
    menu->addAction(m_circleAct);
    menu->addAction(m_arcAct);

    menu = menuBar()->addMenu(tr("&Prop"));
    menu->addAction(m_colorAct);
    menu->addAction(m_thicknessAct);

    QMenu* submenu = new QMenu(QString(tr("Type")));

    submenu->addAction(m_typeSolidAct);
    submenu->addAction(m_typeDashAct);
    submenu->addAction(m_typeDotAct);
    submenu->addAction(m_typeDashDotAct);
    submenu->addAction(m_typeDashDotDotAct);
     menu->addMenu(submenu);

    menu = menuBar()->addMenu(tr("&Zoom"));
    menu->addAction(m_windowAct);
    menu->addAction(m_previousAct);
    menu->addAction(m_allAct);

    menu = menuBar()->addMenu(tr("&Help"));
    menu->addAction(m_helpAct);
    menu->addSeparator();
    menu->addAction(m_aboutAct);

}
void MainWindow::about() {
    QMessageBox *mb = new QMessageBox((QMessageBox::Icon) NULL ,QString(tr("About")),
                                      QString(tr("AutoPac 1.0\n\nDeveloped by Breno and Caio")));
    mb->show();
}
void MainWindow::startLine(qreal x,qreal y){
    if(!m_currentLine){
        m_currentLine = new Line(x,y,x,y);
        m_currentLine->setPen(m_pen);
        //todo
        m_model.addItem(m_currentLine);
    }
}
void MainWindow::updateLine(qreal x,qreal y){
    if(m_currentLine){
        m_currentLine->setEnd(x,y);
    }
}
void MainWindow::startCircle(qreal x,qreal y){
    if(!m_currentCircle){
        m_currentCircle = new Circle(x,y,1);
        m_currentCircle->setPen(m_pen);
        //todo
        m_model.addItem(m_currentCircle);
    }
}
void MainWindow::updateCircle(qreal x,qreal y){
    if(m_currentCircle){
        qreal r = qSqrt( qPow(m_currentCircle->getCenterX()-x,2) + qPow(m_currentCircle->getCenterY()-y,2) );
        m_currentCircle->setRadius(r);
    }
}
void MainWindow::startSelection(qreal x,qreal y){
    if(!m_currentSelection){
        m_currentSelection = new Select(x,y,x,y);
        m_currentSelection->setPen(Qt::DashLine);
        //todo
        m_model.addItem(m_currentSelection);
    }
}
void MainWindow::updateSelection(qreal x,qreal y){
    if(m_currentSelection){
        m_currentSelection->setEnd(x,y);
    }
}

void MainWindow::saveFile() {
    if (m_model.name()){
        QSvgGenerator generator;
        generator.setFileName(m_model.name()->toAscii());
        generator.setSize(QSize(m_view->sceneRect().width(), m_view->sceneRect().height()));
        generator.setViewBox(m_view->sceneRect());
        generator.setTitle(tr("AutoPAC project"));
        QPainter painter(&generator);
        m_view->scene()->render(&painter);
    } else {
        saveAsFile();
    }
}

void MainWindow::saveAsFile() {
    QString* filename = new QString(QFileDialog::getSaveFileName(this, tr("Save AutoPAC Project"), ".", tr("AutoPAC Project (*.pac)")));
    if (!filename->isNull()) {
        m_model.setModelName(*filename);
        QSvgGenerator generator;
        generator.setFileName(*filename);
        generator.setSize(QSize(m_view->sceneRect().width(), m_view->sceneRect().height()));
        generator.setViewBox(m_view->sceneRect());
        generator.setTitle(tr("AutoPAC project"));
        QPainter painter(&generator);
        m_view->scene()->render(&painter);
    }
}

void MainWindow::newProject() {

    m_model.resetModelName();
    m_model.clear();
}

void MainWindow::openFile() {

    QString* filename = new QString(QFileDialog::getOpenFileName(this, tr("Open AutoPAC Project"), ".", tr("AutoPAC Project (*.pac)")));
    if (!filename->isNull()) {
        m_model.setModelName(*filename);
        m_model.clear();
        m_view->scene()->addItem(new QGraphicsSvgItem(*filename));
    }
}
void MainWindow::buildStatusBar() {
    m_statusBarLabel = new QLabel(tr("0,0" ));
    statusBar()->addWidget(m_statusBarLabel);
}
void MainWindow::setBarLabel(QString str) {
    m_statusBarLabel->setText(str);
}
void MainWindow::setLineDrawType(){
    deselect();
    m_lineAct->setChecked(true);
    m_circleAct->setChecked(false);
    m_arcAct->setChecked(false);
    m_drawType = 0;
}
void MainWindow::setCircleDrawType(){
    deselect();
    m_lineAct->setChecked(false);
    m_circleAct->setChecked(true);
    m_arcAct->setChecked(false);
    m_drawType = 1;
}
void MainWindow::setArcDrawType(){
    deselect();
    m_lineAct->setChecked(false);
    m_circleAct->setChecked(false);
    m_arcAct->setChecked(true);
    m_drawType = 2;
}
void MainWindow::selectColor() {
    QColor* color = new QColor(QColorDialog::getColor());
    m_pen.setColor(*color);
}
void MainWindow::zoomIn () {
    deselect();
    m_lineAct->setChecked(false);
    m_circleAct->setChecked(false);
    m_arcAct->setChecked(false);
    m_drawType = 3;
}
void MainWindow::undo(){
    m_commandStack.undo();
}
void MainWindow::redo(){
    m_commandStack.redo();
}

void MainWindow::select(){
    m_selectAct->setChecked(true);
    m_lineAct->setChecked(false);
    m_circleAct->setChecked(false);
    m_arcAct->setChecked(false);
    m_drawType = 4;
}

void MainWindow::deselect(){
    for(QList<QGraphicsItem*>::iterator it=m_selectedItems.begin(); it!=m_selectedItems.end();++it){
        (*it)->setSelected(false);
    }
    m_model.removeItem(m_selectRect);
    m_model.removeItem(m_selectCircle);

    m_selectedItems.clear();
    m_selectAct->setChecked(false);
    m_lineAct->setChecked(false);
    m_circleAct->setChecked(false);
    m_arcAct->setChecked(false);
    m_copyAct->setDisabled(true);
    m_eraseAct->setDisabled(true);
    m_moveAct->setDisabled(true);
    m_rotateAct->setDisabled(true);
    m_scaleAct->setDisabled(true);
}

//---Commands that need to be stacked---

void MainWindow::finishLine(){
    if(m_currentLine){
        m_model.removeItem(m_currentLine);
        m_commandStack.push(new AddItemCmd(&m_model,m_currentLine));
        m_currentLine=NULL;
    }
}
void MainWindow::finishCircle(){
    if(m_currentCircle){
        m_model.removeItem(m_currentCircle);
        m_commandStack.push(new AddItemCmd(&m_model,m_currentCircle));
        m_currentCircle=NULL;
    }
}

void MainWindow::finishSelection(){
    if(m_currentSelection){
        m_model.removeItem(m_currentSelection);
        m_model.removeItem(m_selectRect);
        m_model.removeItem(m_selectCircle);


        for(QList<QGraphicsItem*>::iterator it=m_selectedItems.begin(); it!=m_selectedItems.end();++it){
            (*it)->setSelected(false);
        }

        QList<QGraphicsItem*> temp = m_model.items(m_currentSelection->rect(), Qt::ContainsItemShape);
        if(1){                              //TODO if ctrl is in hold, go to else
            m_selectedItems = temp;
        } else {
            m_selectedItems += temp;
        }

        for(QList<QGraphicsItem*>::iterator it=m_selectedItems.begin(); it!=m_selectedItems.end();++it){
            (*it)->setSelected(true);
        }
        QGraphicsItemGroup *group = m_model.createItemGroup(m_model.selectedItems());
        m_selectRect->setPos(0,0);
        m_selectCircle->setPos(0,0);
        m_selectRect->setRotation(0);
        m_selectCircle->setRotation(0);
        m_selectRect->setRect(group->boundingRect());
        m_selectCircle->setRect(m_selectRect->rect().x()-10,m_selectRect->rect().y()-10,20,20);
        m_model.destroyItemGroup(group);

        delete m_currentSelection;
        m_currentSelection = NULL;

        if(!m_selectedItems.empty()){
            m_model.addItem(m_selectRect);
            m_model.addItem(m_selectCircle);

            m_copyAct->setDisabled(false);
            m_eraseAct->setDisabled(false);
            m_moveAct->setDisabled(false);
            m_rotateAct->setDisabled(false);
            m_scaleAct->setDisabled(false);
        } else {
            m_copyAct->setDisabled(true);
            m_eraseAct->setDisabled(true);
            m_moveAct->setDisabled(true);
            m_rotateAct->setDisabled(true);
            m_scaleAct->setDisabled(true);
        }
    }
}

//Individual stack for these
void MainWindow::finishZoomIn(){
    if(m_currentSelection){
        m_zoomStack.push(new ChangeZoomCmd(m_view,m_currentSelection->rect()));
        m_model.removeItem(m_currentSelection);
        delete m_currentSelection;
        m_currentSelection = NULL;
    }
}

void MainWindow::undoZoom(){
    m_zoomStack.undo();
}

void MainWindow::allZoom(){
    m_zoomStack.clear();
    m_view->fitInView(QRect(0,0,1600,1600), Qt::KeepAspectRatio);
}

void MainWindow::selectThickness(){
    QDialog* thicknessDialog = new QDialog();
    thicknessDialog->setModal(true);

    QGridLayout* layout = new QGridLayout();
    thicknessDialog->setLayout(layout);

    layout->addWidget(m_penWidth,0,1,1,2);

    QPushButton* buttons = new QPushButton(QString(tr("OK")));
    connect(buttons, SIGNAL(clicked()), this, SLOT(setThickness()));
    connect(buttons, SIGNAL(clicked()), thicknessDialog, SLOT(close()));
    layout->addWidget(buttons,1,1);

    buttons = new QPushButton(QString(tr("Cancel")));
    connect(buttons, SIGNAL(clicked()), thicknessDialog, SLOT(close()));
    layout->addWidget(buttons,1,2);

    thicknessDialog->show();

}

void MainWindow::setThickness(){
    m_pen.setWidth(m_penWidth->value());
}

void MainWindow::selectSolidLine(){
    m_typeSolidAct->setChecked(true);
    m_typeDashAct->setChecked(false);
    m_typeDotAct->setChecked(false);
    m_typeDashDotAct->setChecked(false);
    m_typeDashDotDotAct->setChecked(false);
    m_pen.setStyle(Qt::SolidLine);
}

void MainWindow::selectDashLine(){
    m_typeSolidAct->setChecked(false);
    m_typeDashAct->setChecked(true);
    m_typeDotAct->setChecked(false);
    m_typeDashDotAct->setChecked(false);
    m_typeDashDotDotAct->setChecked(false);
    m_pen.setStyle(Qt::DashLine);
}

void MainWindow::selectDotLine(){
    m_typeSolidAct->setChecked(false);
    m_typeDashAct->setChecked(false);
    m_typeDotAct->setChecked(true);
    m_typeDashDotAct->setChecked(false);
    m_typeDashDotDotAct->setChecked(false);
    m_pen.setStyle(Qt::DotLine);
}

void MainWindow::selectDashDotLine(){
    m_typeSolidAct->setChecked(false);
    m_typeDashAct->setChecked(false);
    m_typeDotAct->setChecked(false);
    m_typeDashDotAct->setChecked(true);
    m_typeDashDotDotAct->setChecked(false);
    m_pen.setStyle(Qt::DashDotLine);
}

void MainWindow::selectDashDotDotLine(){
    m_typeSolidAct->setChecked(false);
    m_typeDashAct->setChecked(false);
    m_typeDotAct->setChecked(false);
    m_typeDashDotAct->setChecked(false);
    m_typeDashDotDotAct->setChecked(true);
    m_pen.setStyle(Qt::DashDotDotLine);
}

void MainWindow::selectErase(){
    if(!m_selectedItems.empty())
        m_commandStack.push(new EraseCmd(&m_model,m_selectedItems));
}

bool MainWindow::hitsSelectionBall(qreal x, qreal y){
    QGraphicsRectItem temp(x,y,0.001,0.001);
    return m_selectCircle->collidesWithItem(&temp);
}

void MainWindow::mouseClick(qreal x, qreal y){
    switch(m_drawType){
        case 0:
            startLine(x,y);
            break;

        case 1:
            startCircle(x,y);
            break;

        case 2:
            startArc(x,y);
            break;
        case 3:
            startSelection(x,y);
            break;
        case 4:
            if(hitsSelectionBall(x,y)){
                m_startX = m_selectRect->sceneBoundingRect().x();
                m_startY = m_selectRect->sceneBoundingRect().y();
                m_startW = m_selectRect->sceneBoundingRect().width();
                m_startH = m_selectRect->sceneBoundingRect().height();
                if(m_editType==1){
                    for(QList<QGraphicsItem*>::iterator it = m_selectedItems.begin();it!=m_selectedItems.end();++it){
                         (*it)->setTransformOriginPoint(m_startX+m_startW/2,m_startY+m_startH/2);
                    }
                    m_selectRect->setTransformOriginPoint(m_startX+m_startW/2,m_startY+m_startH/2);
                    m_selectCircle->setTransformOriginPoint(m_startX+m_startW/2,m_startY+m_startH/2);
                }
                m_isEdit=true;

            } else {
                startSelection(x,y);
            }
            break;
    }
}

void MainWindow::mouseRelease(qreal x, qreal y){
    if(m_isEdit){
        m_isEdit = false;
        if(m_editType==0){
            m_commandStack.push(new MoveCmd(&m_model,m_selectedItems,x-m_startX,y-m_startY));
        }
        return;
    }

    switch(m_drawType){
        case 0:
            finishLine();
            break;

        case 1:
            finishCircle();
            break;

        case 2:
            finishArc();
            break;

        case 3:
            finishZoomIn();
            break;
        case 4:
            finishSelection();
            break;
    }
}

void MainWindow::mouseDrag(qreal x, qreal y){
    if(m_isEdit){
        updateSelectedItems(x,y);
    }
    switch(m_drawType){
        case 0:
            updateLine(x,y);
            break;

        case 1:
            updateCircle(x,y);
            break;

        case 2:
            updateArc(x,y);
            break;

        case 3:
        case 4:
            updateSelection(x,y);
            break;
    }
}

void MainWindow::updateSelectedItems(qreal x,qreal y){
    qreal sx;
    qreal sy;
    qreal m_dx;
    qreal m_dy;
    qreal dangle;
    qreal centerX = m_startX + m_startW/2;
    qreal centerY = m_startY + m_startH/2;
    switch(m_editType){
        case 0:
            sx = m_selectRect->sceneBoundingRect().x();
            sy = m_selectRect->sceneBoundingRect().y();
            m_dx = x - sx;
            m_dy = y - sy;
            for(QList<QGraphicsItem*>::iterator it = m_selectedItems.begin();it!=m_selectedItems.end();++it){
                 (*it)->setPos((*it)->x()+m_dx,(*it)->y()+m_dy);
            }
            m_selectRect->setPos(m_selectRect->x()+m_dx,m_selectRect->y()+m_dy);
            m_selectCircle->setPos(m_selectCircle->x()+m_dx,m_selectCircle->y()+m_dy);
            break;
        case 1:
            dangle = qAtan((centerY-y)/(centerX-x));
            dangle = dangle*180/3.1415-qAtan(m_startH/m_startW)*180/3.1415;
            for(QList<QGraphicsItem*>::iterator it = m_selectedItems.begin();it!=m_selectedItems.end();++it){
                (*it)->setRotation(dangle);
            }
            m_selectRect->setRotation(dangle);
            m_selectCircle->setRotation(dangle);

            break;
        case 2:
            sx = m_selectRect->sceneBoundingRect().x();
            sy = m_selectRect->sceneBoundingRect().y();
            m_dx = x - sx;
            m_dy = y - sy;
            for(QList<QGraphicsItem*>::iterator it = m_selectedItems.begin();it!=m_selectedItems.end();++it){
                 (*it)->setScale(0.91);
            }
            m_selectRect->setScale(0.91);
            m_selectCircle->setScale(0.91);
            break;
        case 3:
            break;
    }
}

void MainWindow::selectMove(){
    m_editType=0;
    m_scaleAct->setChecked(false);
    m_rotateAct->setChecked(false);
}
void MainWindow::selectScale(){
    m_editType=2;
    m_moveAct->setChecked(false);
    m_rotateAct->setChecked(false);
}
void MainWindow::selectRotate(){
    m_editType=1;
    m_scaleAct->setChecked(false);
    m_moveAct->setChecked(false);
}

void MainWindow::startArc(qreal x,qreal y){

}

void MainWindow::updateArc(qreal x,qreal y){
}

void MainWindow::finishArc(){
}

void MainWindow::help(){
    QDialog* helpDialog = new QDialog();

    QGridLayout* layout = new QGridLayout();
    helpDialog->setLayout(layout);

    QFile file("/home/caio/pac/tp-pac/tp2/AutoPAC/resources.html");
    file.open(QIODevice::ReadOnly| QIODevice::Text);
    //QTextStream in(file);
    //QTextDocument* td = new QTextDocument(file);
    QTextEdit* te = new QTextEdit();
    te->setHtml(file.readAll());

    layout->addWidget(te);

    helpDialog->show();

}
